package test.multithread;

public class Producer_Consumer {
	static Buffer buf = new Buffer();

	public static void main(String[] args) {
		Producer pro1 = new Producer();
		Producer pro2 = new Producer();
		Consumer con1 = new Consumer();
		Consumer con2 = new Consumer();
		pro1.start();
		pro2.start();
		con1.start();
		con2.start();
		System.out.println("Start!");
	}
}

class Producer extends Thread {

	public void run() {
		// int i=0;
		// while (i<100) {
		// Producer_Consumer.buf.sput(i);
		// System.out.println(i++);
		// }
		int i = 0;

		while (i < 100) {
			synchronized (Producer_Consumer.buf) {
				while (Producer_Consumer.buf.isFull()) {
					try {
						Producer_Consumer.buf.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				Producer_Consumer.buf.put(i);
				System.out.println("             PUT:" + i++ + Thread.currentThread().getName());
				Producer_Consumer.buf.notify();
			}
			try {
				sleep(10);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

}

class Consumer extends Thread {
	public void run() {
		// while (true) {
		// Producer_Consumer.buf.sget();
		// }
		int i = 0;

		while (true) {
			synchronized (Producer_Consumer.buf) {
				while (Producer_Consumer.buf.isEmpty()) {
					try {
						Producer_Consumer.buf.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				i = Producer_Consumer.buf.get();
				System.out.println("GET:" + i+Thread.currentThread().getName());
				Producer_Consumer.buf.notify();
			}
			try {
				sleep(10);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

class Buffer {
	static final int MAX = 10;
	int[] buf = new int[MAX];
	int count = 0;

	boolean isFull() {
		if (count >= MAX)
			return true;
		return false;
	}

	boolean isEmpty() {
		if (count <= 0)
			return true;
		return false;
	}

	void put(int i) {
		buf[count++] = i;
	}

	int get() {
		return buf[--count];
	}

	synchronized void sput(int i) {
		if (isFull()) {
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		buf[count++] = i;
		System.out.println("Producer : " + i);
		notify();
	}

	synchronized void sget() {
		if (count <= 0) {
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println("Conusmer:" + buf[--count]);
		notify();
	}

}
